﻿using System.Web;
using System.Xml;


namespace AnOtherBlog.Core.HttpHandlers
{

	/// <summary>
	/// Genera un archivo xml para los motores de búsqueda 
	/// </summary>

	// TODO: Aprender sobre estas entradas
	//[WebService(Namespace = "http://tempuri.org/")]
	//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	public class SiteMap : IHttpHandler
	{

		#region IHttpHandler Members

		/// <summary>
		/// Enables processing of HTTP Web requests by a custom HttpHandler that 
		/// implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpContext"></see> 
		/// object that provides references to the intrinsic server objects 
		/// (Request, Response, Session, and Server) used to service HTTP requests.
		/// </param>
		public void ProcessRequest(HttpContext context)
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Encoding = System.Text.Encoding.UTF8;
			settings.Indent = true;
			settings.IndentChars = " ";
			settings.NewLineOnAttributes = false;
			settings.OmitXmlDeclaration = false;

			using (XmlWriter writer = XmlWriter.Create(context.Response.OutputStream, settings))
			{
				writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

				PostSiteMap(writer);

				writer.WriteEndElement();
			}

			context.Response.ContentType = "text/xml";
		}

		/// <summary>
		/// Gets a value indicating whether another request can use the 
		/// <see cref="T:System.Web.IHttpHandler"></see> instance.
		/// </summary>
		/// <returns>true if the <see cref="T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
		public bool IsReusable
		{
			get
			{
				return false;
			}
		}

		#endregion

		#region Post SiteMap

		/// <summary>
		/// Genera el bloque de información sobre las publicaciones
		/// </summary>
		/// <param name="writer"></param>
		private void PostSiteMap(XmlWriter writer)
		{
			foreach (Post post in Blog.Current.Posts)
			{
				if (post.IsPublished)
				{
					writer.WriteStartElement("url");
					writer.WriteElementString("loc", post.LinkAbsolute.ToString());
					writer.WriteElementString("lastmod", post.DateModified.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
					writer.WriteElementString("changefreq", "monthly");
					writer.WriteEndElement();
				}
			}
		}

		#endregion

	}

	/*
	 * Google SiteMap 
	 * 
	 * changefreq:
	 * 
	 *	always		
	 *	hourly
	 *	daily
	 *	weekly
	 *	monthly
	 *	yearly
	 *	never
	 * 
	 */

}
